﻿namespace MDXStudio
{
    using MDXParser;
    using MDXStudio.QueryEditor;
    using Microsoft.AnalysisServices.AdomdClient;
    using System;
    using System.Drawing;
    using System.Windows.Forms;

    internal class Intellisense : IntellisenseOptions
    {
        internal AutoCompleteList m_AutoCompleteList;
        private MdxEditor m_Editor;
        private KeyEventArgs m_KeyDown;

        internal void listBoxAutoComplete_DoubleClick(object sender, EventArgs e)
        {
            AutoCompleteList list = (AutoCompleteList) sender;
            if (list.SelectedItems.Count == 1)
            {
                this.selectItem();
                list.Hide();
                this.m_Editor.Focus();
            }
        }

        internal void listBoxAutoComplete_KeyDown(object sender, KeyEventArgs e)
        {
            this.m_Editor.Focus();
        }

        internal void listBoxAutoComplete_SelectedIndexChanged(object sender, EventArgs e)
        {
            this.m_Editor.Focus();
        }

        private void OnIntellisenseMenu_KeyPress(object sender, KeyPressEventArgs e)
        {
        }

        private void OnIntellisenseMenuClick(object sender, EventArgs e)
        {
            ToolStripMenuItem item = (ToolStripMenuItem) sender;
            if (char.IsLetter(this.m_Editor.Text[this.m_Editor.SelectionStart - 1]))
            {
                this.m_Editor.SelectionStart--;
                this.m_Editor.SelectionLength = 1;
            }
            this.m_Editor.SelectedText = item.Text;
        }

        internal void ProcessKeyDownEvent(object sender, KeyEventArgs e)
        {
            this.m_KeyDown = e;
            MdxEditor editor = sender as MdxEditor;
            this.m_Editor = editor;
            if (this.m_AutoCompleteList.Visible)
            {
                if (e.KeyCode == System.Windows.Forms.Keys.Up)
                {
                    this.m_Editor.HideToolTip();
                    if (this.m_AutoCompleteList.SelectedIndex > 0)
                    {
                        this.m_AutoCompleteList.SelectedIndex--;
                    }
                    e.Handled = true;
                }
                else if (e.KeyCode == System.Windows.Forms.Keys.Down)
                {
                    this.m_Editor.HideToolTip();
                    if (this.m_AutoCompleteList.Visible)
                    {
                        if (this.m_AutoCompleteList.SelectedIndex < (this.m_AutoCompleteList.Items.Count - 1))
                        {
                            this.m_AutoCompleteList.SelectedIndex++;
                        }
                        e.Handled = true;
                    }
                }
                else if ((((e.KeyValue < 0x30) || ((e.KeyValue >= 0x3a) && (e.KeyValue <= 0x40))) || ((e.KeyValue >= 0x5b) && (e.KeyValue <= 0x60))) || (e.KeyValue > 0x7a))
                {
                    if ((((e.KeyCode == System.Windows.Forms.Keys.Enter) || (e.KeyCode == System.Windows.Forms.Keys.Tab)) || ((e.KeyCode == System.Windows.Forms.Keys.Space) || (e.KeyCode == System.Windows.Forms.Keys.OemPeriod))) || ((e.KeyCode == System.Windows.Forms.Keys.D9) || (e.KeyCode == System.Windows.Forms.Keys.Oemcomma)))
                    {
                        this.m_Editor.HideToolTip();
                        this.selectItem();
                        if ((e.KeyCode == System.Windows.Forms.Keys.Enter) || (e.KeyCode == System.Windows.Forms.Keys.Tab))
                        {
                            e.Handled = true;
                        }
                    }
                    if ((e.KeyCode != System.Windows.Forms.Keys.ShiftKey) && (e.KeyCode != System.Windows.Forms.Keys.ControlKey))
                    {
                        this.m_AutoCompleteList.Hide();
                    }
                }
                else
                {
                    string str = this.m_Editor.GetCurrentWord() + ((char) e.KeyValue);
                    this.m_AutoCompleteList.SelectedIndex = -1;
                    for (int i = 0; i < this.m_AutoCompleteList.Items.Count; i++)
                    {
                        if (this.m_AutoCompleteList.Items[i].ToString().StartsWith(str, StringComparison.InvariantCultureIgnoreCase))
                        {
                            this.m_AutoCompleteList.SelectedIndex = i;
                            return;
                        }
                    }
                }
            }
        }

        internal void ProcessKeyPressEvent(object sender, KeyPressEventArgs eKeyPress, Connection cn)
        {
            MdxEditor editor = sender as MdxEditor;
            this.m_Editor = editor;
            eKeyPress.Handled = this.m_KeyDown.Handled;
            bool flag = false;
            char keyChar = eKeyPress.KeyChar;
            KeyEventArgs keyDown = this.m_KeyDown;
            if ((!this.m_AutoCompleteList.Visible || (keyChar == '(')) || (keyChar == ','))
            {
                if (keyDown.KeyCode == System.Windows.Forms.Keys.Back)
                {
                    this.m_Editor.HideToolTip();
                    if ((this.m_Editor.SelectionStart <= 1) || !char.IsLetterOrDigit(this.m_Editor.Text[this.m_Editor.SelectionStart - 1]))
                    {
                        this.m_AutoCompleteList.Hide();
                    }
                }
                else if (((')' != keyChar) && ('}' != keyChar)) && (']' != keyChar))
                {
                    DimensionCollection.Enumerator enumerator2;
                    if (System.Windows.Forms.Keys.OemPeriod == keyDown.KeyCode)
                    {
                        string precedingWord = editor.GetPrecedingWord();
                        string str2 = editor.GetPrecedingWord(2);
                        if ((str2 != null) && str2.Equals("MEMBER", StringComparison.InvariantCultureIgnoreCase))
                        {
                            return;
                        }
                        MDXDataType unknown = MDXDataType.Unknown;
                        MDXParser.CubeInfo info = null;
                        if ((cn.MetadataConnection != null) && !string.IsNullOrEmpty(cn.CurrentCube))
                        {
                            info = new AdomdClientCubeInfo(cn.CurrentCube, cn.MetadataConnection);
                        }
                        else
                        {
                            info = new MDXParser.CubeInfo();
                        }
                        if (precedingWord != null)
                        {
                            unknown = info.DetermineType(precedingWord);
                        }
                        this.m_AutoCompleteList.Items.Clear();
                        flag = true;
                        foreach (MDXObject obj2 in MDXParserObjects.s_Objects)
                        {
                            if (((obj2.SyntaxForm == MDXSyntaxForm.Method) || (obj2.SyntaxForm == MDXSyntaxForm.Property)) && (obj2.ThisType == unknown))
                            {
                                int index = (obj2.SyntaxForm == MDXSyntaxForm.Method) ? this.m_AutoCompleteList.ImageList.Images.IndexOfKey("Function.ico") : this.m_AutoCompleteList.ImageList.Images.IndexOfKey("Property.ico");
                                this.m_AutoCompleteList.Items.Add(new AutoCompleteListItem(obj2.CanonicalName, index));
                            }
                        }
                        if (MDXDataType.Level == unknown)
                        {
                            this.m_AutoCompleteList.Items.Add(new AutoCompleteListItem("MEMBERS", this.m_AutoCompleteList.ImageList.Images.IndexOfKey("Property.ico")));
                            this.m_AutoCompleteList.Items.Add(new AutoCompleteListItem("ALLMEMBERS", this.m_AutoCompleteList.ImageList.Images.IndexOfKey("Property.ico")));
                        }
                        if ((precedingWord != null) && (precedingWord.Equals("Measures", StringComparison.InvariantCultureIgnoreCase) || precedingWord.Equals("[Measures]", StringComparison.InvariantCultureIgnoreCase)))
                        {
                            if ((cn != null) && !string.IsNullOrEmpty(cn.CurrentCube))
                            {
                                CubeDef def = cn.MetadataConnection.Cubes[cn.CurrentCube];
                                MeasureCollection.Enumerator enumerator = def.Measures.GetEnumerator();
                                while (enumerator.MoveNext())
                                {
                                    Measure current = enumerator.Current;
                                    this.m_AutoCompleteList.Items.Add(new AutoCompleteListItem(current.Name, this.m_AutoCompleteList.ImageList.Images.IndexOfKey("Measure.ico"), current.UniqueName.Replace("[Measures].", "")));
                                }
                            }
                        }
                        else
                        {
                            HierarchyCollection.Enumerator enumerator3;
                            LevelCollection.Enumerator enumerator4;
                            if (MDXDataType.Level == unknown)
                            {
                                if ((cn != null) && !string.IsNullOrEmpty(cn.CurrentCube))
                                {
                                    CubeDef def2 = cn.MetadataConnection.Cubes[cn.CurrentCube];
                                    bool flag2 = false;
                                    enumerator2 = def2.Dimensions.GetEnumerator();
                                    while (enumerator2.MoveNext())
                                    {
                                        Dimension dimension = enumerator2.Current;
                                        enumerator3 = dimension.Hierarchies.GetEnumerator();
                                        while (enumerator3.MoveNext())
                                        {
                                            Hierarchy hierarchy = enumerator3.Current;
                                            enumerator4 = hierarchy.Levels.GetEnumerator();
                                            while (enumerator4.MoveNext())
                                            {
                                                Level level = enumerator4.Current;
                                                if (level.UniqueName.Equals(precedingWord, StringComparison.InvariantCultureIgnoreCase))
                                                {
                                                    flag2 = true;
                                                    MemberCollection.Enumerator enumerator5 = level.GetMembers(0L, 20L).GetEnumerator();
                                                    while (enumerator5.MoveNext())
                                                    {
                                                        Member member = enumerator5.Current;
                                                        this.m_AutoCompleteList.Items.Add(new AutoCompleteListItem(member.Name, this.m_AutoCompleteList.ImageList.Images.IndexOfKey("Member.ico"), string.Format("[{0}]", member.Name)));
                                                    }
                                                    continue;
                                                }
                                            }
                                        }
                                        if (flag2)
                                        {
                                            break;
                                        }
                                    }
                                }
                            }
                            else if (MDXDataType.Hierarchy == unknown)
                            {
                                if ((cn != null) && !string.IsNullOrEmpty(cn.CurrentCube))
                                {
                                    CubeDef def3 = cn.MetadataConnection.Cubes[cn.CurrentCube];
                                    DimensionCollection.Enumerator enumerator6 = def3.Dimensions.GetEnumerator();
                                    while (enumerator6.MoveNext())
                                    {
                                        Dimension dimension2 = enumerator6.Current;
                                        HierarchyCollection.Enumerator enumerator7 = dimension2.Hierarchies.GetEnumerator();
                                        while (enumerator7.MoveNext())
                                        {
                                            Hierarchy hierarchy2 = enumerator7.Current;
                                            if (hierarchy2.UniqueName.Equals(precedingWord, StringComparison.InvariantCultureIgnoreCase))
                                            {
                                                enumerator4 = hierarchy2.Levels.GetEnumerator();
                                                while (enumerator4.MoveNext())
                                                {
                                                    Level level2 = enumerator4.Current;
                                                    this.m_AutoCompleteList.Items.Add(new AutoCompleteListItem(level2.Name, this.m_AutoCompleteList.ImageList.Images.IndexOfKey("Level2.ico"), string.Format("[{0}]", level2.Name)));
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                            else if (MDXDataType.Dimension == unknown)
                            {
                                if ((cn != null) && !string.IsNullOrEmpty(cn.CurrentCube))
                                {
                                    CubeDef def4 = cn.MetadataConnection.Cubes[cn.CurrentCube];
                                    enumerator2 = def4.Dimensions.GetEnumerator();
                                    while (enumerator2.MoveNext())
                                    {
                                        Dimension dimension3 = enumerator2.Current;
                                        if (dimension3.UniqueName.Equals(precedingWord, StringComparison.InvariantCultureIgnoreCase))
                                        {
                                            enumerator3 = dimension3.Hierarchies.GetEnumerator();
                                            while (enumerator3.MoveNext())
                                            {
                                                Hierarchy hierarchy3 = enumerator3.Current;
                                                this.m_AutoCompleteList.Items.Add(new AutoCompleteListItem(hierarchy3.Name, this.m_AutoCompleteList.ImageList.Images.IndexOfKey("Hierarchy.ico"), string.Format("[{0}]", hierarchy3.Name)));
                                            }
                                        }
                                    }
                                }
                            }
                            else if (cn == null)
                            {
                            }
                        }
                    }
                    else if (',' == keyChar)
                    {
                        if (this.m_AutoCompleteList.Visible)
                        {
                            this.selectItem();
                        }
                    }
                    else if ('(' == keyChar)
                    {
                        if (this.m_AutoCompleteList.Visible)
                        {
                            this.selectItem();
                        }
                        string currentWord = editor.GetCurrentWord();
                        if (currentWord != null)
                        {
                            MDXObject obj3 = MDXParserObjects.FindMDXObject(currentWord);
                            if ((obj3 != null) && (obj3.SyntaxTip != null))
                            {
                                editor.ShowToolTip(string.Format("{0}({1})", obj3.CanonicalName, obj3.SyntaxTip));
                            }
                        }
                    }
                    else if ('[' == keyChar)
                    {
                        this.m_AutoCompleteList.Items.Clear();
                        flag = true;
                        if ((cn != null) && !string.IsNullOrEmpty(cn.CurrentCube))
                        {
                            CubeDef def5 = cn.MetadataConnection.Cubes[cn.CurrentCube];
                            enumerator2 = def5.Dimensions.GetEnumerator();
                            while (enumerator2.MoveNext())
                            {
                                Dimension dimension4 = enumerator2.Current;
                                this.m_AutoCompleteList.Items.Add(new AutoCompleteListItem(dimension4.Name, this.m_AutoCompleteList.ImageList.Images.IndexOfKey("DbDimension.ico"), string.Format("{0}]", dimension4.Name)));
                            }
                        }
                        else
                        {
                            this.m_AutoCompleteList.Items.Add(new AutoCompleteListItem("Measures", this.m_AutoCompleteList.ImageList.Images.IndexOfKey("DbDimension.ico"), "Measures]"));
                        }
                    }
                    else if (System.Windows.Forms.Keys.Enter == keyDown.KeyCode)
                    {
                        editor.HideToolTip();
                    }
                    else if (System.Windows.Forms.Keys.Space == keyDown.KeyCode)
                    {
                        this.m_AutoCompleteList.Items.Clear();
                        flag = true;
                        string str4 = editor.GetPrecedingWord();
                        string str5 = editor.GetPrecedingWord(2);
                        if (str4 != null)
                        {
                            if (str4.Equals("FROM", StringComparison.InvariantCultureIgnoreCase))
                            {
                                if ((cn.MetadataConnection != null) && (cn.MetadataConnection.Cubes.Count > 0))
                                {
                                    CubeCollection.Enumerator enumerator8 = cn.MetadataConnection.Cubes.GetEnumerator();
                                    while (enumerator8.MoveNext())
                                    {
                                        CubeDef def6 = enumerator8.Current;
                                        if (def6.Type == CubeType.Cube)
                                        {
                                            this.m_AutoCompleteList.Items.Add(new AutoCompleteListItem(def6.Name, this.m_AutoCompleteList.ImageList.Images.IndexOfKey("Cube.ico"), string.Format("[{0}]", def6.Name)));
                                        }
                                    }
                                }
                                else
                                {
                                    editor.ShowToolTip("If you were connected to the server, you would've seen the list of cubes now", 0x5dc);
                                }
                            }
                            else if (str4.Equals("ON", StringComparison.InvariantCultureIgnoreCase))
                            {
                                int num4 = this.m_AutoCompleteList.ImageList.Images.IndexOfKey("Keyword.ico");
                                this.m_AutoCompleteList.Items.Add(new AutoCompleteListItem("0", num4));
                                this.m_AutoCompleteList.Items.Add(new AutoCompleteListItem("1", num4));
                                this.m_AutoCompleteList.Items.Add(new AutoCompleteListItem("COLUMNS", num4));
                                this.m_AutoCompleteList.Items.Add(new AutoCompleteListItem("ROWS", num4));
                                this.m_AutoCompleteList.Items.Add(new AutoCompleteListItem("PAGES", num4));
                            }
                            else if ((str5 != null) && str5.Equals("FROM", StringComparison.InvariantCultureIgnoreCase))
                            {
                                this.m_AutoCompleteList.Items.Add(new AutoCompleteListItem("WHERE", this.m_AutoCompleteList.ImageList.Images.IndexOfKey("Keyword.ico")));
                                this.m_AutoCompleteList.Items.Add(new AutoCompleteListItem("CELL PROPERTIES", this.m_AutoCompleteList.ImageList.Images.IndexOfKey("Keyword.ico")));
                            }
                        }
                    }
                    else if ((!keyDown.Control && !keyDown.Alt) && char.IsLetter(keyChar))
                    {
                        bool flag3 = false;
                        if ((this.m_Editor.SelectionStart > 0) && char.IsLetter(this.m_Editor.Text[this.m_Editor.SelectionStart - 1]))
                        {
                            flag3 = true;
                        }
                        if (!flag3)
                        {
                            this.m_AutoCompleteList.Items.Clear();
                            flag = true;
                            string str6 = this.m_Editor.GetCurrentWord() + keyChar;
                            foreach (string str7 in MDXParserObjects.s_Keywords)
                            {
                                if (str7.StartsWith(str6, StringComparison.InvariantCultureIgnoreCase))
                                {
                                    this.m_AutoCompleteList.Items.Add(new AutoCompleteListItem(str7, this.m_AutoCompleteList.ImageList.Images.IndexOfKey("Keyword.ico")));
                                }
                            }
                            foreach (MDXObject obj4 in MDXParserObjects.s_Objects)
                            {
                                if (((obj4.SyntaxForm == MDXSyntaxForm.Function) && (obj4.Optimization != MDXFunctionOpt.Deprecated)) && obj4.CanonicalName.StartsWith(str6, StringComparison.InvariantCultureIgnoreCase))
                                {
                                    this.m_AutoCompleteList.Items.Add(new AutoCompleteListItem(obj4.CanonicalName, this.m_AutoCompleteList.ImageList.Images.IndexOfKey("Function.ico")));
                                }
                            }
                            if ((cn != null) && !string.IsNullOrEmpty(cn.CurrentCube))
                            {
                                CubeDef def7 = cn.MetadataConnection.Cubes[cn.CurrentCube];
                                enumerator2 = def7.Dimensions.GetEnumerator();
                                while (enumerator2.MoveNext())
                                {
                                    Dimension dimension5 = enumerator2.Current;
                                    if (dimension5.Name.StartsWith(str6, StringComparison.InvariantCultureIgnoreCase))
                                    {
                                        this.m_AutoCompleteList.Items.Add(new AutoCompleteListItem(dimension5.Name, this.m_AutoCompleteList.ImageList.Images.IndexOfKey("DbDimension.ico"), dimension5.UniqueName));
                                    }
                                }
                            }
                        }
                    }
                }
                else
                {
                    char ch2 = '\0';
                    switch (keyChar)
                    {
                        case ')':
                            ch2 = '(';
                            break;

                        case ']':
                            ch2 = '[';
                            break;

                        case '}':
                            ch2 = '{';
                            break;
                    }
                    int selectionStart = editor.SelectionStart;
                    int num2 = editor.FindMatch(keyChar, ch2);
                    if (num2 >= 0)
                    {
                        editor.SelectedText = keyChar.ToString();
                        editor.SelectionStart = num2;
                        editor.SelectionLength = 1;
                        editor.SelectionBackColor = Color.Silver;
                        editor.SelectionStart = selectionStart;
                        editor.SelectionLength = 1;
                        editor.SelectionBackColor = Color.Silver;
                        editor.SelectionStart = selectionStart + 1;
                        editor.SelectionLength = 0;
                        eKeyPress.Handled = true;
                        editor.HideToolTip();
                    }
                }
                if (flag && (this.m_AutoCompleteList.Items.Count > 0))
                {
                    bool flag4 = false;
                    bool flag5 = false;
                    ColorCoding colorCoding = this.m_Editor.ColorCoding;
                    if (colorCoding != null)
                    {
                        ColorSegment segment = colorCoding.FindSegment(editor.SelectionStart, editor.SelectionStart);
                        if (segment != null)
                        {
                            if (segment.Color == Color.Green)
                            {
                                flag4 = true;
                            }
                            else if (segment.Color == Color.Maroon)
                            {
                                flag5 = string.IsNullOrEmpty(editor.GetCurrentWord());
                            }
                        }
                        else if (editor.SelectionStart == editor.TextLength)
                        {
                            int num5 = editor.SelectionStart - 1;
                            while (num5 >= 0)
                            {
                                if ((editor.Text[num5] == '[') || (editor.Text[num5] == ']'))
                                {
                                    break;
                                }
                                num5--;
                            }
                            if (num5 >= 0)
                            {
                                flag5 = editor.Text[num5] == '[';
                            }
                        }
                    }
                    if (!flag4 && !flag5)
                    {
                        this.m_Editor.HideToolTip();
                        Point positionFromCharIndex = editor.GetPositionFromCharIndex(editor.SelectionStart);
                        if (positionFromCharIndex.Y < (editor.ClientSize.Height / 2))
                        {
                            positionFromCharIndex.Y += ((int) Math.Ceiling((double) editor.Font.GetHeight())) + 4;
                        }
                        else
                        {
                            positionFromCharIndex.Y -= this.m_AutoCompleteList.ClientSize.Height;
                        }
                        positionFromCharIndex.X += 4;
                        if ((positionFromCharIndex.X + this.m_AutoCompleteList.ClientSize.Width) > editor.ClientRectangle.Right)
                        {
                            positionFromCharIndex.X = editor.ClientRectangle.Right - this.m_AutoCompleteList.ClientSize.Width;
                        }
                        Point p = editor.PointToScreen(positionFromCharIndex);
                        this.m_AutoCompleteList.Location = this.m_AutoCompleteList.Parent.PointToClient(p);
                        this.m_AutoCompleteList.BringToFront();
                        this.m_AutoCompleteList.Show();
                    }
                }
            }
        }

        internal void ProcessMouseDownEvent(object sender, MouseEventArgs e)
        {
            MdxEditor editor = sender as MdxEditor;
            this.m_Editor = editor;
            this.m_AutoCompleteList.Hide();
            this.m_Editor.HideToolTip();
        }

        private void selectItem()
        {
            AutoCompleteListItem selectedItem = this.m_AutoCompleteList.SelectedItem as AutoCompleteListItem;
            if (selectedItem != null)
            {
                string text = selectedItem.Text;
                if (selectedItem.Tag != null)
                {
                    text = selectedItem.Tag.ToString();
                }
                string currentWord = this.m_Editor.GetCurrentWord();
                this.m_Editor.SelectionStart -= currentWord.Length;
                this.m_Editor.SelectionLength = currentWord.Length;
                this.m_Editor.SelectedText = "";
                this.m_Editor.SelectionLength = 0;
                this.m_Editor.SelectedText = text;
            }
            this.m_AutoCompleteList.Hide();
        }
    }
}

